/**
 * 商品推荐管理
 */
var queryRecommendSearch = function() {
	var queryRecommendFieldSet = new Ext.form.FieldSet({
				id : 'queryRecommendFieldSet',
				title : '查询条件',
				collapsible : true,// 可折叠
				buttonAlign : 'center',
				keys : [{
							key : 13, // 13代表回车
							fn : queryRecommend,
							scope : this
						}],
				items : [{
					layout : 'column',
					border : false,
					items : [{
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
							id : 'rcommendGoodsId',
							fieldLabel : '商品名称',
							xtype : 'goodsCmb',
							allowBlank : true,
							hiddenName : 'goodsId',
							showValue : true,
							existall : true,
							defaultFirstRow : 1,
							statusArr : [0, 1],
							listeners : {
								'select' : function() {
									var goodsId = Ext.getCmp("rcommendGoodsId")
											.getValue();
								}
							}
						}, {
							xtype : "datefield",
							id : "recommendStartDate",
							name : "recommendStartDate",
							fieldLabel : "开始日期",
							format : "Y-m-d",// 日期的格式
							width : 175,
							editable : false,
							listeners : {
								'select' : function() {
									var start = Ext
											.getCmp('recommendStartDate')
											.getValue();
									Ext.getCmp('recommendEndDate')
											.setMinValue(start);
									var recommendEndDate = Ext
											.getCmp('recommendEndDate')
											.getValue();
									if (start > recommendEndDate
											&& recommendEndDate != "") {
										Ext.getCmp('recommendEndDate')
												.setValue(start);
									}
								}
							}
						}]
					}, {
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									xtype : 'dataDictionaryCmb',
									anchor : '100%',
									fieldLabel : '推荐类型',
									hiddenName : "recommendType",
									editable : false,
									autoLoad : false,
									existall : true,
									defaultFirstRow : 1,
									dictionaryType : PmsUtil.recommend_type
								}, {
									columnWidth : .25,
									layout : 'form',
									border : false,
									items : [{
										width : 175,
										id : "recommendEndDate",
										xtype : "datefield",
										name : "recommendEndDate",
										fieldLabel : "结束日期",
										editable : false,
										format : "Y-m-d",// 日期的格式
										listeners : {
											'select' : function() {
												var startDate = Ext
														.getCmp('recommendStartDate')
														.getValue();
												Ext.getCmp('recommendEndDate')
														.setMinValue(startDate);
												var endDate = Ext
														.getCmp('recommendEndDate')
														.getValue();
												Ext
														.getCmp('recommendStartDate')
														.setMaxValue(endDate);

											}
										}
									}]
								}]
					}, {
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									xtype : 'dataDictionaryCmb',
									anchor : '100%',
									fieldLabel : '是否热门',
									hiddenName : "isHot",
									editable : false,
									autoLoad : false,
									existall : true,
									defaultFirstRow : 1,
									dictionaryType : PmsUtil.recommend_is_hot
								}, {
									layout : 'column',
									border : false,
									items : [{
												text : '查询',
												xtype : 'button',
												width : 80,
												handler : function() {
													queryRecommend();
												},
												style : {
													marginLeft : "100px",
													marginRight : "10px"
												}
											}, {
												text : '重置',
												xtype : 'button',
												width : 80,
												handler : function() {
													Ext
															.getCmp('queryRecommendForm')
															.getForm().reset();
													// 对日期的初始设置
													Ext
															.getCmp('recommendStartDate')
															.setMaxValue(new Date());
													Ext
															.getCmp('recommendEndDate')
															.setMinValue("");
												}
											}]
								}]
					}, {
						columnWidth : .25,
						layout : 'form',
						border : false,
						items : [{
									xtype : 'dataDictionaryCmb',
									anchor : '100%',
									fieldLabel : '状态',
									hiddenName : "recommendStatus",
									editable : false,
									autoLoad : false,
									existall : true,
									defaultFirstRow : 1,
									dictionaryType : PmsUtil.recommend_status
								}]
					}]
				}]
			});
	fieldSetListeners(['queryRecommendFieldSet', 'queryRecommendForm',
					'recommendManagerGrid'], [0.16, 0.84]);

	var queryRecommendForm = new Ext.form.FormPanel({
				id : 'queryRecommendForm',
				anchor : '100% 16%',
				frame : true,
				labelAlign : 'right',
				bodyBorder : false,
				items : [queryRecommendFieldSet]
			});
	return queryRecommendForm;
};

/**
 * grids
 */
var recommendManagerGrid = function() {
	var recommendManagerSm = new Ext.grid.CheckboxSelectionModel();// 创建选择模式对象
	// 定义表的每列（对应表头信息）
	var recommendManagerCm = new Ext.grid.ColumnModel([
			new Ext.grid.RowNumberer(), {
				dataIndex : "id",
				header : "推荐编号",
				sortable : true,
				width : 70
			}, {
				dataIndex : "goodsName",
				header : "商品名称",
				sortable : true,
				width : 80
			}, {
				dataIndex : "recommendType",
				header : "推荐类型",
				sortable : true,
				width : 80,
				renderer : function(value) {
					return PmsUtil.RecommendType(value);

				}
			}, {
				dataIndex : "goodsPic",
				header : "商品图",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.ShowPicture(value);

				}
			}, {
				dataIndex : "goodsDefalutPrice",
				header : "商品单价",
				sortable : true,
				width : 100,
				renderer : function(value) {
					return PmsUtil.Price(value);

				}
			}, {
				dataIndex : "recommendOrder",
				header : "排序",
				sortable : true,
				width : 60,
				editor : {
					xtype : 'textfield'
				}
			}, {
				dataIndex : "recommendStatus",
				header : "状态",
				sortable : true,
				width : 80,
				renderer : function(value) {
					if (value == 0) {
						return '<div style="color:red;">'
								+ PmsUtil.RecommendStatus(value) + '</div>';
					}
					return PmsUtil.RecommendStatus(value);
				}
			}, {
				dataIndex : "isHot",
				header : "是否热门",
				sortable : true,
				width : 100,
				renderer : function(value) {
					if (value == 1) {
						return '<div style="color:red;">'
								+ PmsUtil.IsHot(value) + '</div>';
					}
					return PmsUtil.IsHot(value);
				}
			}, {
				dataIndex : "startDate",
				header : "开始时间",
				sortable : true,
				width : 130
			}, {
				dataIndex : "endDate",
				header : "结束时间",
				sortable : true,
				width : 130

			}, {
				dataIndex : "createdName",
				header : "创建人",
				sortable : true,
				width : 100
			}, {
				dataIndex : "createdDate",
				header : "创建时间",
				sortable : true,
				width : 130
			}, {
				header : "管理",
				width : 140,
				dataIndex : "id",
				sortable : false,
				renderer : function(j, i, g, m, h) {
					var l = g.data.id;
					var recommendStatus = g.data.recommendStatus;
					var recommendisHot = g.data.isHot;
					var k = "";

					if (isGranted("recommendManager_取消推荐")) {
						if (recommendStatus == "0") {
							k += '&nbsp;&nbsp;<a href="#" onclick="updRecommendstatus('
									+ l
									+ ','
									+ "1"
									+ ','
									+ "0"
									+ ','
									+ "'取消推荐'" + ')\" >取消推荐</a>';
						}

					}
					if (isGranted("recommendManager_推荐")) {
						if (recommendStatus == "1") {
							k += '&nbsp;&nbsp;<a href="#" onclick="updRecommendstatus('
									+ l
									+ ','
									+ "0"
									+ ','
									+ recommendisHot
									+ ',' + "'推荐'" + ')\" >推荐</a>';
						}
					}
					if (isGranted("recommendManager_热门")) {
						if (recommendisHot == "0") {
							k += '&nbsp;&nbsp;<a href="#" onclick="updRecommendIsHot('
									+ l
									+ ','
									+ "1"
									+ ','
									+ "'热门'"
									+ ')\" >热门</a>';
						}
					}
					if (isGranted("recommendManager_取消热门")) {
						if (recommendisHot == "1") {
							k += '&nbsp;&nbsp;<a href="#" onclick="updRecommendIsHot('
									+ l
									+ ','
									+ "0"
									+ ','
									+ "'取消热门'"
									+ ')\" >取消热门</a>';
						}
					}
					return k;
				}
			}]);

	// 定义分析器
	var recommendManagerReader = new Ext.data.JsonReader({
				totalProperty : "totalCount",
				root : "list",
				fields : [{
							name : "id"
						}, {
							name : "goodsId"
						}, {
							name : "goodsName"
						}, {
							name : "goodsPic"
						}, {
							name : "goodsDefalutPrice"
						}, {
							name : "startDate"
						}, {
							name : "endDate"
						}, {
							name : "isHot"
						}, {
							name : "recommendType"
						}, {
							name : "recommendStatus"
						}, {
							name : "recommendOrder"
						}, {
							name : "startDate"
						}, {
							name : "endDate"
						}, {
							name : "createdName"
						}, {
							name : "createdDate"
						}, {
							name : "updatedName"
						}, {
							name : "updatedDate"
						}]
			});

	// 取数据store
	var recommendViewStore = new Ext.data.Store({
				autoLoad : true,// 要加载数据必须设置为true
				proxy : new Ext.data.HttpProxy({
							url : __ctxPath
									+ "/recommendManager/selectRecommends"
						}),
				remoteSort : false,
				baseParams : {
					start : 0,
					limit : 25
				},
				listeners : {
					beforeload : {
						fn : function(thiz, options) {
							Ext.apply(thiz.baseParams, Ext
											.getCmp('queryRecommendForm')
											.getForm().getValues());
						}
					}
				},
				reader : recommendManagerReader
			});

	// 定义grid的toolbar
	var recommendManagerTb = new Ext.Toolbar({
				id : "recommendManagerTb",
				height : 25,
				items : []
			});

	recommendManagerTb.add(new Ext.scm.Button({
				text : "添加推荐",
				iconCls : "btn-add",
				width : 80,
				hsValue : 'recommendManager_添加推荐',
				pressed : true,
				listeners : {
					"click" : function() {
						addRecommend();
					}
				}
			}));

	recommendManagerTb.add(new Ext.scm.Button({
				text : "批量修改",
				iconCls : "btn-edit",
				width : 80,
				pressed : true,
				hsValue : "recommendManager_批量修改",
				listeners : {
					"click" : function() {
						updRecommendsOrder();
					}
				}
			}));

	recommendManagerTb.add(new Ext.Toolbar.Spacer());
	recommendManagerTb.add(new Ext.scm.Button({
				text : "刷 新",
				iconCls : "btn-refresh",
				width : 80,
				hsValue : 'recommendManager_刷新',
				pressed : true,
				handler : function() {
					queryRecommend();
				}
			}));
	var recommendManagerGrid = new Ext.grid.EditorGridPanel({
				id : 'recommendManagerGrid',
				store : recommendViewStore,
				cm : recommendManagerCm,
				sm : recommendManagerSm,
				autoScroll : true,
				clicksToEdit : 1,
				loadMask : true,
				trackMouseOver : true,
				stripeRows : true,
				columnLines : true,
				loadMask : {
					msg : "正在加载数据，请稍侯……"
				},
				viewConfig : {
					emptyText : '没有您想要的数据!'
				},
				anchor : '100% 84%',
				frame : true,
				tbar : recommendManagerTb,
				bbar : new PG.PagingBar({
							store : recommendViewStore
						})
			});
	return recommendManagerGrid;
};

// 查询
function queryRecommend() {
	var grid = Ext.getCmp("recommendManagerGrid");
	var form = Ext.getCmp("queryRecommendForm");
	if (form.getForm().isValid()) {
		var gridStore = grid.getStore();
		gridStore.baseParams = Ext.apply(gridStore.baseParams, form.getForm()
						.getValues());
		gridStore.load();
	}
}

// 添加推荐
function addRecommend() {
	try {
		addRecommendWin(null, "添加推荐").show();
	} catch (Error) {
		Ext.Loader.load([__ctxPath + '/js/recommend/addRecommend.js'],
				function() {
					addRecommendWin(null, "添加推荐").show();
				});
	}
}

// 修改商品推荐状态
function updRecommendstatus(recommendId, status, recommendisHot, message) {
	Ext.Msg.confirm("信息确认", "是否" + message + "该商品?", function(btn) {
		if (btn == "yes") {
			var optionMask = new Ext.LoadMask(Ext.getBody(), {
						msg : "正在处理,请稍后..."
					});
			optionMask.show();
			Ext.Ajax.request({
				url : __ctxPath + "/recommendManager/updateRecommendStatusById",
				params : {
					recommendId : recommendId,
					status : status,
					recommendisHot : recommendisHot
				},
				method : "post",
				success : function(response) {
					optionMask.hide();
					var jsonData = Ext.util.JSON.decode(response.responseText);
					if (jsonData.success) {
						Ext.MessageBox.show({
									title : "信息提示",
									msg : jsonData.data,
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.INFO
								});
						queryRecommend();
					} else {
						Ext.MessageBox.show({
									title : "错误提示",
									msg : jsonData.data,
									buttons : Ext.MessageBox.OK,
									icon : Ext.MessageBox.ERROR
								});
					}
				},
				failure : function(response) {
					optionMask.hide();
					Ext.MessageBox.show({
								title : "操作信息",
								msg : "服务器请求异常,请稍后再试!",
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.ERROR
							});
				}
			});
		}
	});
}

// 修改商品是否热门
function updRecommendIsHot(recommendId, recommendisHot, message) {
	Ext.Msg.confirm("信息确认", "是将该商品否设为" + message + "商品?", function(btn) {
		if (btn == "yes") {
			var optionMask = new Ext.LoadMask(Ext.getBody(), {
						msg : "正在处理,请稍后..."
					});
			optionMask.show();
			Ext.Ajax.request({
						url : __ctxPath + "/recommendManager/updRecommendIsHot",
						params : {
							recommendId : recommendId,
							recommendisHot : recommendisHot
						},
						method : "post",
						success : function(response) {
							optionMask.hide();
							var jsonData = Ext.util.JSON
									.decode(response.responseText);
							if (jsonData.success) {
								Ext.MessageBox.show({
											title : "信息提示",
											msg : jsonData.data,
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.INFO
										});
								queryRecommend();
							} else {
								Ext.MessageBox.show({
											title : "错误提示",
											msg : jsonData.data,
											buttons : Ext.MessageBox.OK,
											icon : Ext.MessageBox.ERROR
										});
							}
						},
						failure : function(response) {
							optionMask.hide();
							Ext.MessageBox.show({
										title : "操作信息",
										msg : "服务器请求异常,请稍后再试!",
										buttons : Ext.MessageBox.OK,
										icon : Ext.MessageBox.ERROR
									});
						}
					});
		}
	});
}

/**
 * 修改排序
 */
function updRecommendsOrder() {
	var modiRecords = Ext.getCmp("recommendManagerGrid").getStore()
			.getModifiedRecords();
	if (modiRecords.length == 0) {
		Ext.MessageBox.show({
					title : '提示',
					msg : '当前没有数据修改',
					buttons : Ext.MessageBox.OK,
					icon : Ext.MessageBox.WARNING
				});
		return;
	};

	var recommendsUpdArr = new Array();
	for (var i = 0; i < modiRecords.length; i++) {
		var temrecord = new Ext.data.Record();
		temrecord.set("id", modiRecords[i].data.id);
		temrecord.set("recommendOrder", modiRecords[i].data.recommendOrder);
		recommendsUpdArr.push(temrecord.data);
	}
	var jsonList = Ext.encode(recommendsUpdArr);

	Ext.Msg.confirm("信息确认", "是否批量修改推荐排序？", function(btn) {
				if (btn == 'yes') {
					var optionMask = new Ext.LoadMask(Ext.getBody(), {
								msg : "正在处理,请稍后..."
							});
					optionMask.show();
					Ext.Ajax.request({
								url : __ctxPath
										+ "/recommendManager/updRecommendsOrder",
								params : {
									jsonList : Ext.util.Format.htmlDecode(Ext
											.encode(recommendsUpdArr)).trim()
								},
								method : "post",
								success : function(response) {
									optionMask.hide();
									var jsonData = Ext.util.JSON
											.decode(response.responseText);
									if (jsonData.success) {
										Ext.MessageBox.show({
													title : "信息提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.INFO
												});
										queryRecommend();
									} else {
										Ext.MessageBox.show({
													title : "错误提示",
													msg : jsonData.data,
													buttons : Ext.MessageBox.OK,
													icon : Ext.MessageBox.ERROR
												});
									}
								},
								failure : function(response) {
									optionMask.hide();
									Ext.MessageBox.show({
												title : "操作信息",
												msg : "服务器请求异常,请稍后再试!",
												buttons : Ext.MessageBox.OK,
												icon : Ext.MessageBox.ERROR
											});
								}

							});
				}
			});

}

Ext.getCmp("centerTabPanel").getActiveTab().add(queryRecommendSearch(),
		recommendManagerGrid());
Ext.getCmp("centerTabPanel").getActiveTab().doLayout();
